package com.zsck.zsgy.jpush;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.core.app.NotificationManagerCompat;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.google.gson.Gson;
import com.zsck.zsgy.util.Constants;

import cn.jpush.android.api.CustomMessage;
import cn.jpush.android.api.JPushMessage;
import cn.jpush.android.api.NotificationMessage;
import cn.jpush.android.service.JPushMessageReceiver;


public class MyJPushReceiver extends JPushMessageReceiver {




    /**
     * TODO 连接极光服务器
     */
    @Override
    public void onConnected(Context context, boolean b) {
        super.onConnected(context, b);
        LogUtils.e("连接极光服务器", "onConnected");
    }

    /**
     * TODO 注册极光时的回调
     */
    @Override
    public void onRegister(Context context, String s) {
        super.onRegister(context, s);
        LogUtils.e("注册极光时的回调", "onRegister" + s);
    }

    /**
     * TODO 注册以及解除注册别名时回调
     */
    @Override
    public void onAliasOperatorResult(Context context, JPushMessage jPushMessage) {
        super.onAliasOperatorResult(context, jPushMessage);
        LogUtils.e("注册以及解除注册别名时回调", jPushMessage.toString());
    }

    /**
     * TODO 接收到推送下来的通知
     *      可以利用附加字段（notificationMessage.notificationExtras）来区别Notication,指定不同的动作,附加字段是个json字符串
     *      通知（Notification），指在手机的通知栏（状态栏）上会显示的一条通知信息
     */
    @Override
    public void onNotifyMessageArrived(Context context, NotificationMessage notificationMessage) {
//        super.onNotifyMessageArrived(context, notificationMessage);
//        int appAlive = AppUtil.isAppAlive(context, AppUtils.getAppPackageName());
        NotificationManagerCompat notification = NotificationManagerCompat.from(context);
        boolean isEnabled = notification.areNotificationsEnabled();

        LogUtils.e("isEnabled:"+isEnabled+"接收到推送下来的通知 "+ notificationMessage.toString());


    }

    private static String[] MSG_TYPE = new String[]{"tenancyContract","billMessage","activeMessage",
            "propertyFix","notice","electronicInvoice","smartDerice"};

    /**
     * TODO 打开了通知
     *      notificationMessage.notificationExtras(附加字段)的内容处理代码
     *      比如打开新的Activity， 打开一个网页等..
     */
    @Override
    public void onNotifyMessageOpened(Context context, NotificationMessage notificationMessage) {
        String notificationExtras =notificationMessage.notificationExtras;
        JNotificationMessage message = new Gson().fromJson(notificationExtras, JNotificationMessage.class);
        String extras = message.getExtras();
        String title = "";
        Message messagea = new Gson().fromJson(extras, Message.class);
        String type = messagea.getType();
        int JUMPTYPE=0;
        switch (type){
            case "tenancyContract":
                title="合同租务";
                JUMPTYPE=1;
                break;
            case "billMessage":
                title="账单消息";
                JUMPTYPE=1;
                break;
            case "activeMessage":
                title="活动消息";
                JUMPTYPE=3;
                break;
            case "propertyFix":
                title="物业报修";
                JUMPTYPE=1;
                break;
            case "notice":
                title="通知公告";
                JUMPTYPE=1;
                break;
            case "electronicInvoice":
                title="电子发票";
                JUMPTYPE=1;
                break;
            case "smartDerice":
                title="智能设备";
                JUMPTYPE=2;
                break;
        }

        boolean appRunning = AppUtils.isAppRunning(AppUtils.getAppPackageName());
        if(appRunning){
//            jumpNotiDetail();
           /* Intent intent= new Intent(context,MessageNotificationListActivity.class);
            intent.putExtra("TITLE", title);
            intent.putExtra("type",type);
            intent.putExtra("TYPE", JUMPTYPE);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);*/

        }else{//应用被杀死
            Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(AppUtils.getAppPackageName());
            // 设置flag
            launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            Bundle bundle = new Bundle();
            // 传递的数据
            // 设置跳转标志符
            launchIntent.putExtra("jpushIntentTag", bundle);
            context.startActivity(launchIntent, bundle);
        }

    }

    private void jumpNotiDetail() {
    /*if ("contract_pass".equals(messagea.getSubType())) {
        Intent intent = new Intent(context, SubscriptionInformationActivity.class);
        Map<String, Object> map = new Gson().fromJson(messagea.getJumpParams(), HashMap.class);
        intent.putExtra("contractId", map.get("contractId").toString());
        intent.putExtra("contractType", map.get("contractType").toString());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        return;
    }*/
           /* String url = NetConfig.HOST + "h5" + messagea.getJumpLink();
            String jumpParams = messagea.getJumpParams();
            if (!TextUtils.isEmpty(jumpParams)) {
                try {
                    Map<String, Object> map = new Gson().fromJson(jumpParams, HashMap.class);
                    String params = "?";
                    for (String key : map.keySet()) {
                        params += key + "=" + URLEncoder.encode(map.get(key).toString(), "utf-8") + "&";
                    }
                    params.substring(0, params.length() - 1);
                    url += params;
                } catch (Exception e) {
                    LogUtil.e("fuck", e.getMessage());
                }
            }
            Intent intent = new Intent(context,WebViewActivity.class);
            intent.putExtra("url",url);
            intent.putExtra("showTitle",true);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);*/
    }


    /**
     * TODO 接收到推送下来的自定义消息
     *      自定义消息不是通知，默认不会被SDK展示到通知栏上，极光推送仅负责透传给SDK。其内容和展示形式完全由开发者自己定义。
     *      自定义消息主要用于应用的内部业务逻辑和特殊展示需求
     */
    @Override
    public void onMessage(Context context, CustomMessage customMessage) {
        super.onMessage(context, customMessage);
        // 收到消息 显示通知
        LogUtils.e("接收到推送下来的自定义消息", "onMessage: "+customMessage);

    }

    //通知
    private void processCustomMessage(Context context, String message) {
/*
        String channelID = "1";
        String channelName = "channel_name";

        // 跳转的Activity
        Intent intent = new Intent(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);

        //适配安卓8.0的消息渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
        }

        NotificationCompat.Builder notification =
                new NotificationCompat.Builder(context, channelID);

        notification.setAutoCancel(true)
                .setContentText(message)
                .setContentTitle("我是Title")
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setDefaults(Notification.DEFAULT_ALL)
                .setContentIntent(pendingIntent);

        notificationManager.notify((int)(System.currentTimeMillis()/1000), notification.build());
    */
    }



}
